#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@File   : test03_extstorage.py
@Time : 2024/12/24 10:51
@Author: Wangwc
@Describe:  ……
"""
import time
import allure
import pytest

from business.DiskApi import DiskApi
from commons.logger import log
from utils.login import Login


# TODO 当前模块的配置文件名称，配置在config目录下
config_name = 'cloud.ini'
login = Login(config_name=config_name)

global_token = None

@pytest.fixture(scope="function")
def init_api():
    global global_token
    login.http_request.update_base_url()
    if global_token is None:
        global_token = login.login()
    api = DiskApi(global_token, configname=config_name)
    api.http.update_base_url()
    return api


def handle_api_call(api_method, *args, attach_to_allure=True, format_result=None, **kwargs):
    if not callable(api_method):
        raise TypeError("api_method 参数必须是可调用对象（如函数或方法）")
    if attach_to_allure is not None and not isinstance(attach_to_allure, bool):
        raise TypeError("attach_to_allure 参数必须是布尔类型或者为 None")
    if format_result is not None and not callable(format_result):
        raise TypeError("format_result 参数必须是可调用对象（如函数）或者为 None")

    max_retries = 3
    for retry in range(max_retries):
        try:
            result = api_method(*args, **kwargs)
            if attach_to_allure:
                if format_result:
                    formatted_result = format_result(result)
                else:
                    formatted_result = str(result)
                allure.attach(formatted_result, f"{api_method.__name__} 调用结果", allure.attachment_type.TEXT)
            log.info(f"{api_method.__name__} 调用成功")
            return result
        except Exception as e:
            allure.attach(str(e), f"{api_method.__name__} 调用错误信息", allure.attachment_type.TEXT)
            log.error(f"{api_method.__name__} 调用出现错误: {e}", exc_info=True)
            # 假设根据错误信息判断 token 过期
            if "token 过期" in str(e) and retry < max_retries - 1:
                global global_token
                global_token = login.login()
                api_method.__self__.token = global_token
                continue
            elif isinstance(e, ConnectionError):
                log.error("连接错误，可能是网络问题，请检查网络连接。")
            elif isinstance(e, ValueError):
                log.error("值错误，可能是传入的参数有误，请检查参数。")
            raise


@allure.feature("外部存储管理")
class TestStorageManagement():
    @allure.title("获取外接设备信息")
    def test_get_extstorage_information(self, init_api):
        with allure.step("获取外接设备信息"):
            extstorage_info = handle_api_call(init_api.get_extStorage_list)
            usb_list = extstorage_info.get("usb_list")
            assert usb_list != [], "获取外接设备信息失败"

    @allure.title("获取外接设备文件信息")
    def test_get_extstorage_files(self, init_api):
        with allure.step("获取外接设备文件信息"):
            extstorage_info = handle_api_call(init_api.get_extStorage_list)
            usb_list = extstorage_info.get("usb_list")
            partition = usb_list[0].get('partition')
            mnt_path = partition[0].get('mnt_path') if partition[0].get('mnt_path') else partition[1].get('mnt_path')
            extstorage_info = handle_api_call(init_api.get_extStorage_files,mnt_path)
            left_tree = extstorage_info.get("left_tree")
            right_files = extstorage_info.get("right_files")
            assert left_tree.get("files") is not None, "获取外接设备文件信息失败"
            assert right_files.get("files") is not None, "获取外接设备文件信息失败"

    @allure.title("设置外接设备ext4延迟配置")
    def test_set_extstorage_ext4(self, init_api):
        with allure.step("设置ext4延迟配置开启"):
            handle_api_call(init_api.set_extStorage_setting,delay_allocation=True)
            setting_info = handle_api_call(init_api.get_extStorage_setting)
            assert setting_info.get('delay_allocation') == True, "设置ext4延迟配置开启失败"


        with allure.step("设置ext4延迟配置关闭"):
            handle_api_call(init_api.set_extStorage_setting,delay_allocation=False)
            setting_info = handle_api_call(init_api.get_extStorage_setting)
            assert setting_info.get('delay_allocation') == False, "设置ext4延迟配置开启失败"
        #
        # with allure.step("设置禁止使用USB存储设备"):
        #     init_api.set_extStorage_setting(disable_usb_storage=True)
        #     setting_info = init_api.get_extStorage_setting()
        #     assert setting_info.get('disable_usb_storage') == True, "设置禁止使用USB存储设备失败"
        #
    @allure.title("设置是否允许使用USB")
    def test_set_extstorage_usb(self, init_api):
        with allure.step("设置允许使用USB存储设备"):
            handle_api_call(init_api.set_extStorage_setting,disable_usb_storage=False)
            setting_info = handle_api_call(init_api.get_extStorage_setting)
            assert setting_info.get('disable_usb_storage') == False, "设置允许使用USB存储设备失败"

    @allure.title("设置普通用户外部设备权限")
    def test_set_extstorage_generaluser(self, init_api):
        with allure.step("设置禁止用户允许访问外部存储设备"):
            handle_api_call(init_api.set_extStorage_setting,normal_user_can_access=False)
            setting_info = handle_api_call(init_api.get_extStorage_setting)
            assert setting_info.get('normal_user_can_access') == False, "设置禁止用户允许访问外部存储设备失败"


        with allure.step("设置普通用户允许访问外部存储设备"):
            init_api.set_extStorage_setting(normal_user_can_access=True)
            setting_info = handle_api_call(init_api.get_extStorage_setting)
            assert setting_info.get('normal_user_can_access') == True, "设置普通用户允许访问外部存储设备失败"



